#include "Item.h"
#include "Game.h"
#include "StringLib.h"
#include "Util.h"
#include "GameState.h"

Item::Item(GenericType type, Status status) : GameObject(type) {
	m_weight = 10;
	m_status = status;
	m_statusIdentified = false;
	m_equipped = false;
	m_equipLocation = NUM_EQUIPMENT_LOCATIONS;
	m_stackable = false;
	m_numStacked = 1;
	m_parentList = NULL;
}

Item::~Item() {
}

Item::Item(GenericType type, std::ifstream& file) : GameObject(type) {
	int* tokens = Util::intSplit(file);
	m_statusIdentified = tokens[0] == 1;
	m_status = Status(tokens[1]);
	m_equipped = tokens[2] == 1;
	m_equipLocation = EquipmentLocation(tokens[3]);
	m_numStacked = tokens[4];
	m_weight = 10;
	m_stackable = false;
	m_parentList = NULL;
	delete[] tokens;
}

void Item::save(std::ofstream& file) const {
	file << (m_statusIdentified ? 1 : 0) << " " << m_status << " " << (m_equipped ? 1 : 0) << " " << m_equipLocation << " " << m_numStacked << "\n";
}

void Item::logDetails(TextLog& log) const {
	GameObject::logDetails(log);
	log.addBlankLine();
	log.addLine(g_stringLib->getTextString(ST_ITEM_WEIGHT, Util::intToString(m_numStacked * getWeight()).c_str()));
}

std::string Item::getName() const {
	return getItemName();
}

std::string Item::getItemName(int mod) const {
	int numStacked = m_numStacked - mod;
	std::string name = numStacked > 1 ? getPluralName() : GameObject::getBasicName();
	if(m_statusIdentified)
		name = g_stringLib->getMiscString(MST_STATUS, m_status) + " " + name;
	if(numStacked > 1)
		name = Util::intToString(numStacked) + " " + name;
	return name;
}

std::string Item::getPluralName() const {
	return g_stringLib->getObjectString((*(m_types.rbegin())).first, (*(m_types.rbegin())).second, 2);
}

int Item::getRandomDamage() const {
	return rand_plus_one(4);
}

bool Item::isIdentified() const {
	return g_idDatabase[getSpecificTypeCategory()][getSpecificType()];
}

void Item::identify() {
	g_idDatabase[getSpecificTypeCategory()][getSpecificType()] = true;
}

void Item::statusIdentify() {
	m_statusIdentified = true;
}

void Item::setStatus(Status status, bool overwrite) {
	if(overwrite || status < m_status) {
		m_status = status;
	}
}

std::string Item::getColoredName() const {
	return getColoredItemName();
}

std::string Item::getColoredItemName(int mod) const {
	std::string color = Util::intToString(m_statusIdentified ? m_status : 3);
	return "\r" + color + getItemName(mod) + "\r" + color;
}

std::string Item::getColoredBasicName() const {
	std::string color = Util::intToString(m_statusIdentified ? m_status : 3);
	return "\r" + color + getBasicName() + "\r" + color;
}

void Item::reduceStackCount(int num, bool destroy, std::list<Item*>* items) {
	m_numStacked -= num;
	if(destroy && m_numStacked <= 0) {
		if(items != NULL)
			items->remove(this);
		g_gameState->markForDeletion(this);
	}
}
